package com.anclick.mywatch;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ConfigSub1Activity extends Activity {

	private static final String TAG = "MyWatch";
	
	private static final String DOMAIN = "http://jun2yah.dothome.co.kr";
	private static final String[] mThemeFile = {
		"ani_clock1.zip", 
		"ani_clock2.zip",
		"ani_clock3.zip",
		"Text_Bclock1.zip",
		"Text_Bclock2.zip",
		"Text_Bclock3.zip",
		"Text_Wclock1.zip",
		"Text_Wclock2.zip",
		"Text_Wclock3.zip"
	};
	
	private Integer[] mThumbIds = {
			R.drawable.clock_01, 
			R.drawable.clock_01, 
			R.drawable.clock_01,
			R.drawable.clock_02, 
			R.drawable.clock_02, 
			R.drawable.clock_02,
			R.drawable.clock_03, 
			R.drawable.clock_03, 
			R.drawable.clock_03
	};
	
	private static int mPosition;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.config_sub1);

		GridView grid = (GridView) findViewById(R.id.grid);
		grid.setAdapter(new MyAdapter(this));

		grid.setOnItemClickListener(new GridView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Toast.makeText(ConfigSub1Activity.this, "download-" + position, Toast.LENGTH_SHORT).show();
				
				mPosition = position;
				
				downloadTheme(DOMAIN + "/" + mThemeFile[mPosition]);
				
				UnzipRunnable runnable = new UnzipRunnable();
				Thread thread = new Thread(runnable);
				thread.setDaemon(true);
				thread.start();
			}
		});
	}

	public void downloadTheme(String fileUrl) {
		try {   

			URL url = new URL(fileUrl);

			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);

			urlConnection.connect();

			File SDCardRoot = Environment.getExternalStorageDirectory();
			File file = new File(SDCardRoot, ConfigSub2Activity.SUB_PATH + "/" + mThemeFile[mPosition]);

	        if (file.exists()) {
	            file.delete();
	        } else {
	            //file.createNewFile();
	        }

			FileOutputStream fileOutput = new FileOutputStream(file);

			InputStream inputStream = urlConnection.getInputStream();
			int totalSize = urlConnection.getContentLength();
			int downloadedSize = 0;

			byte[] buffer = new byte[1024];
			int bufferLength = 0;

			while ( (bufferLength = inputStream.read(buffer)) > 0 ) {   
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
			}

			fileOutput.close();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 

	public class Decompress { 
		private String mZipFile; 
		private String mLocation; 

		public Decompress(String zipFile, String location) { 
			mZipFile = zipFile; 
			mLocation = location; 

			dirChecker(""); 
		} 

		public void unzip() { 
			try  { 
				FileInputStream fin = new FileInputStream(mZipFile); 
				ZipInputStream zin = new ZipInputStream(fin); 
				ZipEntry ze = null; 
				
				int count = 0;
				
				while ((ze = zin.getNextEntry()) != null) {
					count++;
					Log.v("Decompress", "Unzipping " + ze.getName()); 
					zin.closeEntry(); 
				}
				
				Log.v("Decompress", "count = " + count); 
				
				while ((ze = zin.getNextEntry()) != null) { 
					Log.v("Decompress", "Unzipping " + ze.getName()); 

					if (ze.isDirectory()) { 
						dirChecker(ze.getName()); 
					} else { 
						FileOutputStream fout = new FileOutputStream(mLocation + ze.getName()); 
						for (int c = zin.read(); c != -1; c = zin.read()) { 
							fout.write(c); 
						} 

						zin.closeEntry(); 
						fout.close(); 
					} 
				} 
				zin.close(); 
			} catch(Exception e) { 
				Log.e("Decompress", "unzip", e); 
			} 
		} 

		private void dirChecker(String dir) { 
			File f = new File(mLocation + dir); 

			if(!f.isDirectory()) { 
				f.mkdirs(); 
			}
		} 
	}
	
	class UnzipRunnable implements Runnable {
		public void run() {
			String zipFile = Environment.getExternalStorageDirectory() + ConfigSub2Activity.SUB_PATH + "/" + mThemeFile[mPosition]; 
			String unzipLocation = Environment.getExternalStorageDirectory() + ConfigSub2Activity.SUB_PATH + "/"; 
			 
			Decompress d = new Decompress(zipFile, unzipLocation); 
			d.unzip(); 
		}
	}
	
	class MyAdapter extends BaseAdapter {

		private Context mContext;

		public MyAdapter(Context c) {
			mContext = c;
		}

		public int getCount() {
			return mThumbIds.length;
		}

		public Object getItem(int position) {
			return mThumbIds[position];
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view;

			if (convertView == null) {
				view = new View(mContext);
				LayoutInflater inflater = getLayoutInflater();
				view = inflater.inflate(R.layout.icon, parent, false);
			} else {
				view = (View)convertView;
			}

			ImageView imageView = (ImageView)view.findViewById(R.id.img_icon);
			imageView.setImageResource(mThumbIds[position]);

			TextView textView = (TextView)view.findViewById(R.id.text_icon);
			textView.setTextSize(10);
			textView.setText(mThemeFile[position].replace(".zip", ""));

			/// !!!별점 어떻게 주냐?
			//			RatingBar ratingBar = (RatingBar)findViewById(R.id.ratingBar1);
			//			ratingBar.setRating(3.0f);

			return view;
		}
	}
}


